from flask import Flask, render_template
import pandas as pd
import json
from pyecharts.charts import Map
from pyecharts.charts import Bar
from pyecharts.charts import Line
from pyecharts.charts import Grid
from pyecharts.charts import Pie
from pyecharts.charts import Scatter
from pyecharts import options as opts
from pyecharts.charts import Page, WordCloud
from pyecharts.globals import SymbolType
import numpy as np
import seaborn as sns
import warnings
import os
from pyecharts.charts import Bar, Grid, Line, Pie, Tab
from pyecharts.commons.utils import JsCode

train_data = pd.read_excel('数据.xlsx')



app = Flask(__name__)


@app.route('/')
def hello_world():
	train_data = pd.read_excel('数据.xlsx')
	g = train_data.groupby('城区')
	train_data_region = g.count()['小区']
	region = train_data_region.index.tolist()
	count = train_data_region.values.tolist()
	new = [x + '区' for x in region]
	m = (
	        Map(init_opts=opts.InitOpts(theme='dark'))
	        .add('', [list(z) for z in zip(new, count)], '广州')
	        .set_global_opts(
	            title_opts=opts.TitleOpts(
	                                      subtitle='从数据来看，可以看到目前二手房市场比较火热的区域，番禺二手房数量最多，其次是增城区，近几年正在改造建设，有赶超之势。\n从化区是二手房源最少的地区，仅有201套。',
	                                      pos_left="1%"),
	            visualmap_opts=opts.VisualMapOpts(max_=3000),
	        )
	    )
	m.render('templates/广州市二手房分布情况.html')

	with open("templates/广州市二手房分布情况.html", encoding="utf8", mode="r") as f:
		plot_all = "".join(f.readlines())

	return render_template('样式1.html',
	     the_plot_all = plot_all,
	     the_title='广州市二手房分布情况')






@app.route('/junjia')
def junjia():
	train_data = pd.read_excel('数据.xlsx')
	temp = train_data.groupby(['小区'])['总价/万'].mean().reset_index()
	data_pair = sorted([(row['小区'], round(row['总价/万']/1000, 1))
	                    for _, row in temp.iterrows()], key=lambda x: x[1], reverse=True)[:15]

	bar = (Bar(init_opts=opts.InitOpts(theme='dark'))
	       .add_xaxis([x[0] for x in data_pair])
	       .add_yaxis('二手房均价', [x[1] for x in data_pair])
	       .set_series_opts(label_opts=opts.LabelOpts(is_show=True, font_style='italic'),
	                            itemstyle_opts=opts.ItemStyleOpts(
	                                color=JsCode("""new echarts.graphic.LinearGradient(0, 1, 0, 0, 
	                                             [{
	                                                 offset: 0,
	                                                 color: 'rgb(0,206,209)'
	                                             }, {
	                                                 offset: 1,
	                                                 color: 'rgb(218,165,32)'
	                                             }])"""))
	                            )
	       .set_global_opts(
	           title_opts=opts.TitleOpts(title="均价TOP15小区",subtitle='从数据来看，较高总价的为3400万，且在天河区的热门楼盘较多。',
	           	pos_left="50%"),
	           legend_opts=opts.LegendOpts(is_show=False),
	           tooltip_opts=opts.TooltipOpts(formatter='{b}:{c}万元'))
	      )



	bar.render('templates/广州市二手房总价TOP15.html')

	with open("templates/广州市二手房总价TOP15.html", encoding="utf8", mode="r") as f:
		plot_all = "".join(f.readlines())

	return render_template('样式1.html',
	     the_plot_all = plot_all,
	     the_title='广州市二手房总价TOP15')





@app.route('/sandian')
def sandian():
	train_data = pd.read_excel('数据.xlsx')
	scatter = (Scatter(init_opts=opts.InitOpts(theme='dark'))
           .add_xaxis(train_data['面积/平方米'])
           .add_yaxis("房价", train_data['总价/万'])
           .set_series_opts(label_opts=opts.LabelOpts(is_show=False),
                           markpoint_opts=opts.MarkPointOpts(data=[opts.MarkPointItem(type_="max", name="最大值"),]))
           .set_global_opts(
               legend_opts=opts.LegendOpts(is_show=False),
               title_opts=opts.TitleOpts(title="总价-面积 散点图"),
               xaxis_opts=opts.AxisOpts(
                   name='面积',
                   # 设置坐标轴为数值类型
                   type_="value", 
                   # 不显示分割线
                   splitline_opts=opts.SplitLineOpts(is_show=False)),
               yaxis_opts=opts.AxisOpts(
                   name='总价',
                   name_location='middle',
                   # 设置坐标轴为数值类型
                   type_="value",
                   # 默认为False表示起始为0
                   is_scale=True,
                   splitline_opts=opts.SplitLineOpts(is_show=False),),
               visualmap_opts=opts.VisualMapOpts(is_show=True, type_='color', min_=100, max_=1000)
    ))

	scatter.render('templates/面积与总价关系.html')

	with open("templates/面积与总价关系.html", encoding="utf8", mode="r") as f:
		plot_all = "".join(f.readlines())

	return render_template('样式1.html',
	     the_plot_all = plot_all,
	     the_title='面积与总价关系')



@app.route('/chaoxiang')
def chaoxiang():
	train_data = pd.read_excel('数据.xlsx')
	g = train_data.groupby('朝向')
	g.count()['小区']
	train_data_direction =  g.count()['小区']
	train_data_direction
	directions = train_data_direction.index.tolist()
	count = train_data_direction.values.tolist()

	c1 = (
    Pie(init_opts=opts.InitOpts(theme='dark'))
        .add(
        '',
        [list(z) for z in zip(directions, count)],
        radius=['20%', '60%'],
        center=['40%', '50%'],
#         rosetype="radius",
        label_opts=opts.LabelOpts(is_show=True),
        )    
        .set_global_opts(title_opts=opts.TitleOpts(
                                                   subtitle='由上述数据显示二手房源朝向为南的最为多，占了总比的38%，说明市场广阔，人们也较为偏好朝向为南的房屋。',
                                                   pos_left='1%'),
                        legend_opts=opts.LegendOpts(type_="scroll", pos_left="80%",pos_top="25%",orient="vertical")
                        )
        .set_series_opts(label_opts=opts.LabelOpts(formatter='{b}:{c} ({d}%)'),position="outside")
    )

	c1.render('templates/房屋朝向.html')

	with open("templates/房屋朝向.html", encoding="utf8", mode="r") as f:
		plot_all = "".join(f.readlines())

	return render_template('样式1.html',
	     the_plot_all = plot_all,
	     the_title='房屋朝向')



@app.route('/huxing')
def huxing():
	train_data = pd.read_excel('数据.xlsx')
	
	temp = train_data.groupby(['户型'])['小区'].count().reset_index()
	data_pair = sorted([(row['户型'], row['小区'])
	                    for _, row in temp.iterrows()], key=lambda x: x[1], reverse=True)[:10]

	pie = (Pie(init_opts=opts.InitOpts(theme='dark'))
	       .add('', data_pair,
	            radius=["30%", "75%"],
	            rosetype="radius")
	       .set_global_opts(title_opts=opts.TitleOpts(title="广州二手房 户型分布",subtitle='3室2厅、2室1厅、3室1厅的房源\n占据了市场的主导地位',pos_left="75%"),
	                       legend_opts=opts.LegendOpts(is_show=False),)
	       .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {d}%"))
	      )

	pie.render('templates/房源户型.html')

	with open("templates/房源户型.html", encoding="utf8", mode="r") as f:
		plot_all = "".join(f.readlines())

	return render_template('样式1.html',
	     the_plot_all = plot_all,
	     the_title='房源户型')


@app.route('/jiage')
def jiage():
	train_data = pd.read_excel('数据.xlsx')

	g = train_data.groupby('城区')
	df_region = g.count()['小区']
	region = df_region.index.tolist()
	count = df_region.values.tolist()
	df_region
	df_price = g.mean()['总价/万']
	df_price
	
	df_price = g.mean()['总价/万']
	price = [round(x,2) for x in df_price.values.tolist()]
	bar = (
	    Bar(init_opts=opts.InitOpts(theme='dark'))
	    .add_xaxis(region)
	    .add_yaxis('数量', count,
	              label_opts=opts.LabelOpts(is_show=True))
	    .extend_axis(
	        yaxis=opts.AxisOpts(
	            name="均价/万",
	            type_="value",
	            min_=200,
	            max_=900,
	            interval=100,
	            axislabel_opts=opts.LabelOpts(formatter="{value}"),
	        )
	    )
	    .set_global_opts(
	        tooltip_opts=opts.TooltipOpts(
	            is_show=True, trigger="axis", axis_pointer_type="cross"
	        ),
	        xaxis_opts=opts.AxisOpts(
	            type_="category",
	            axispointer_opts=opts.AxisPointerOpts(is_show=True, type_="shadow"),
	        ),
	        yaxis_opts=opts.AxisOpts(name='数量',
	            axistick_opts=opts.AxisTickOpts(is_show=True),
	            splitline_opts=opts.SplitLineOpts(is_show=False),)
	    )
	)
	line2 = (
	    Line()
	    .add_xaxis(xaxis_data=region)
	    .add_yaxis(
	 
	        series_name="均价/万",
	        yaxis_index=1,
	        y_axis=price,
	        label_opts=opts.LabelOpts(is_show=True),
	        z=10)
	)
	bar.overlap(line2)
	grid = Grid()
	grid.add(bar, opts.GridOpts(pos_left="5%", pos_right="20%"), is_control_axis_index=True)


	bar.render('templates/房源及价格折线.html')

	with open("templates/房源及价格折线.html", encoding="utf8", mode="r") as f:
		plot_all = "".join(f.readlines())

	return render_template('样式1.html',
	     the_plot_all = plot_all,
	     the_title='房源及价格折线')


@app.route('/guanzhu')
def guanzhu():

	train_data = pd.read_excel('数据.xlsx')
	train_data['建造时间'] = train_data['其他信息'].str.split('|').str[5].str.split('年').str[0]
	g = train_data.groupby('建造时间')
	train_data_guanzhu = g.count()['关注人数']
	train_data_guanzhu

	guanzhu = train_data_guanzhu.index.tolist()
	count = train_data_guanzhu.values.tolist()
	bar = (
	    Bar(init_opts=opts.InitOpts(theme='dark'))
	    .add_xaxis(guanzhu)
	    .add_yaxis('数量', count)
	    .set_global_opts(
	    	title_opts=opts.TitleOpts(
	    		subtitle='比对不同年份建造的房子与关注人数，\n可以得出1998-2000或是2012-2014这八年\n是人们最为偏好的房子建设年份',
	    		pos_left="70%"),
	        yaxis_opts=opts.AxisOpts(name='关注人数'),
	        xaxis_opts=opts.AxisOpts(name='建造时间'),
	        datazoom_opts=opts.DataZoomOpts(type_='slider')
	    )
	)

	bar.render('templates/地区关注数.html')

	with open("templates/地区关注数.html", encoding="utf8", mode="r") as f:
		plot_all = "".join(f.readlines())

	return render_template('样式1.html',
	     the_plot_all = plot_all,
	     the_title='地区关注数')




if __name__ == '__main__':
    app.run(debug=True)
